-- add_requires("linux-headers", {system = false, configs = {driver_modules = true}})
-- add_packages("linux-headers")

target("miscdevice")
    add_rules("platform.linux.driver")
    set_values("linux.driver.linux-headers", "/lib/modules/5.15.85-1-MANJARO/build")
    -- set_values("linux.driver.linux-headers", "example")
    add_files("*.c")
    add_cflags("-O2") -- 不加 -O2 会报错，不知道为啥


    on_install("linux|x86_64", function (package)
        import("core.project.depend")

        -- 检测驱动是否已经安装，如果已经安装，先卸载
        local basename = package:basename()
        local modules = os.iorun("sudo lsmod")
        local installed = modules:match(basename)
        print(installed)
        if installed then
            os.vrunv("sudo rmmod " .. basename)
        end
        
        local targetfile = package:targetfile() -- build/linux/x86_64/release/testdriver.ko
        os.vrunv("sudo insmod " .. targetfile)

        local info = os.iorun("sudo dmesg")
        -- print(info)
        if info then
            -- print the lines that contain the module name
            for line in info:gmatch("[^\r\n]+") do
                if line:find(basename) then
                    print(line)
                end
            end
        end
    end)

    on_uninstall("linux|x86_64", function(package)
        import("core.project.depend")
        local basename = package:basename() -- build/linux/x86_64/release/testdriver.ko
        os.vrunv("sudo rmmod " .. basename)

        local info = os.iorun("sudo dmesg")
        -- print(info)
        if info then
            -- print the lines that contain the module name
            for line in info:gmatch("[^\r\n]+") do
                if line:find(basename) then
                    print(line)
                end
            end
        end
    end)

target_end()
